import React, { Component } from 'react'
import './Header.css'
export default class Header extends Component {
  state = {
    todoName: '',
  }
  // 配合受控组件的函数
  handle = (e) => {
    this.setState({
      todoName: e.target.value.trim(),
    })
  }
  keyDownhandle = (e) => {
    // 判断是否是回车键,如果不是则return
    //如果todoName的值是空字符串,直接return
    if (e.keyCode !== 13 || !this.state.todoName) return

    // 将todoName传递给App组件
    const { getTodoName } = this.props
    getTodoName(this.state.todoName)

    // 清空文本框
    this.setState({
      todoName: '',
    })
  }
  render() {
    const { todoName } = this.state

    return (
      <div className="todo-header">
        <input
          type="text"
          value={todoName}
          onChange={this.handle}
          onKeyDown={this.keyDownhandle}
        />
      </div>
    )
  }
}
